<?php

namespace plugin\admin\app\controller;


use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use plugin\admin\app\model\Pet;
use support\Request;
use support\Response;
use plugin\admin\app\model\RedeemCode;
use support\exception\BusinessException;
use think\Exception;

/**
 * 兑换码管理 
 */
class RedeemCodeController extends Crud
{
    
    /**
     * @var RedeemCode
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new RedeemCode;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('redeem-code/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {

            $code_num = $request->post('code_num', 0);
            if (empty($code_num)) {
                return $this->json(1, '兑换码数量不能为空');
            }
            $pet_id = $request->post('pet_id', 0);
            $pet = Pet::find($pet_id);
            if (!$pet) {
                return $this->json(1, '宠物不存在');
            }
            $redeem_codes = RedeemCode::pluck('code');
            $redeem_codes = $redeem_codes->toArray();
            for ($i = 0; $i < $code_num; $i++) {
                $code = $this->generate_code();
                while (in_array($code, $redeem_codes)) {
                    $code = $this->generate_code();
                }
                $redeem_codes[] = $code;
                $data = [
                    'code' => $code,
                    'pet_id' => $pet_id,
                    'created_at' => date('Y-m-d H:i:s'),
                ];
                $this->model->insert($data);
            }
            return $this->json(0, '兑换码添加成功');
        }
        return view('redeem-code/insert');
    }

    protected function generate_code(){
        $code = '';
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $max = strlen($chars) - 1;
        for ($i = 0; $i < 6; $i++) {
            $code.= $chars[random_int(0, $max)];
        }
        return $code;
    }

    public function download_file(Request $request)
    {
        $file_path = base_path(). '/plugin/admin/public/upload/files/template.xlsx';
        // 下载文件
        return response()->download($file_path, '兑换码模版.xlsx');
    }


    public function excel(Request $request)
    {
        $file = current($request->file());
        if (!$file || !$file->isValid()) {
            return $this->json(1, '未找到文件');
        }

        $data = $this->base($request, '/upload/files/' . date('Ymd'));
        $filePath = $data['realpath'];
        // 获取文件扩展名
        $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));

        try {
            if ($extension === 'xlsx') {
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
            } elseif ($extension === 'xls') {
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
            } elseif ($extension === 'csv') {
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
                $reader->setDelimiter(','); // 设置分隔符
            } else {
                return $this->json(1, '不支持的文件格式');
            }
            $spreadsheet = $reader->load($filePath);
            $sheet = $spreadsheet->getSheet(0);
            $highestRow = $sheet->getHighestRow();
            $data = [];
            for ($row = 2; $row <= $highestRow; $row++) {
                //$serial_number = $sheet->getCellByColumnAndRow(1, $row)->getValue();
                $code = $sheet->getCellByColumnAndRow(2, $row)->getValue();
                $pet_id = $sheet->getCellByColumnAndRow(3, $row)->getValue();
                $data[] = [
                    'code' => $code,
                    'pet_id' => $pet_id,
                    'created_at' => date('Y-m-d H:i:s'),
                ];
            }

            $redeem_codes = RedeemCode::pluck('code');
            $redeem_codes = $redeem_codes->toArray();

            //提取有效兑换码 $data中的 code
            $valid_data  = array_column($data, 'code');
            var_dump($redeem_codes,$valid_data);


            //取交集 $valid_data 与 $redeem_codes 数组的交集
            $intersect = array_intersect($valid_data, $redeem_codes);

            if ($intersect) {
                return $this->json(1, '导入失败，兑换码不能重复');
            }

            //获取宠物ID
            $pet_ids = Pet::pluck('id');
            //提取有效宠物ID $data中的 pet_id
            $valid_pet_ids = array_column($data, 'pet_id');

            //取$pet_ids在$valid_pet_ids没有的元素
            $pet_ids_diff = array_diff($valid_pet_ids, $pet_ids->toArray());
            var_dump($pet_ids_diff);
            if ($pet_ids_diff) {
                return $this->json(1, '导入失败，宠物ID不存在');
            }

            (new RedeemCode)->insert($data);
        } catch (\Exception $e) {
            return $this->json(1, '导入失败');
        }
        return $this->json(0, '导入成功', $data);
    }
    /**
     * 获取上传数据
     * @param Request $request
     * @param $relative_dir
     * @return array
     * @throws BusinessException|\Random\RandomException
     */
    protected function base(Request $request, $relative_dir): array
    {
        $relative_dir = ltrim($relative_dir, '\\/');
        $file = current($request->file());
        if (!$file || !$file->isValid()) {
            throw new BusinessException('未找到上传文件', 400);
        }

        $admin_public_path = rtrim(config('plugin.admin.app.public_path', ''), '\\/');
        $base_dir = $admin_public_path ? $admin_public_path . DIRECTORY_SEPARATOR : base_path() . '/plugin/admin/public/';
        $full_dir = $base_dir . $relative_dir;
        if (!is_dir($full_dir)) {
            mkdir($full_dir, 0777, true);
        }

        $ext = $file->getUploadExtension() ?: null;
        $mime_type = $file->getUploadMimeType();
        $file_name = $file->getUploadName();
        $file_size = $file->getSize();

        if (!$ext && $file_name === 'blob') {
            [$___image, $ext] = explode('/', $mime_type);
            unset($___image);
        }

        $ext = strtolower($ext);
        $ext_forbidden_map = ['php', 'php3', 'php5', 'css', 'js', 'html', 'htm', 'asp', 'jsp'];
        if (in_array($ext, $ext_forbidden_map)) {
            throw new BusinessException('不支持该格式的文件上传', 400);
        }

        $relative_path = $relative_dir . '/' . bin2hex(pack('Nn', time(), random_int(1, 65535))) . ".$ext";
        $full_path = $base_dir . $relative_path;
        $file->move($full_path);
        $image_with = $image_height = 0;
        if ($img_info = getimagesize($full_path)) {
            [$image_with, $image_height] = $img_info;
            $mime_type = $img_info['mime'];
        }
        return [
            'url' => "/app/admin/$relative_path",
            'name' => $file_name,
            'realpath' => $full_path,
            'size' => $file_size,
            'mime_type' => $mime_type,
            'image_with' => $image_with,
            'image_height' => $image_height,
            'ext' => $ext,
        ];
    }


    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('redeem-code/update');
    }

}
